package org.jground.zk.util;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jground.util.StringUtils;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Desktop;
import org.zkoss.zk.ui.Session;

public class ZKUtils {

    private static Log logger = LogFactory.getLog(ZKUtils.class);

    public static void removeAllChildren(Component parent) {
        List<Component> children = parent.getChildren();
        if (children != null) {
            List<Component> copiedList = new ArrayList<Component>(children);
            for (Component child : copiedList) {
                parent.removeChild(child);
            }
        }
    }

    public static void makeInvisibleExcept(Component parent, Component exceptionComponent) {

        List<Component> children = parent.getChildren();
        for (Component child : children) {
            if (child != exceptionComponent) {
                child.setVisible(false);
            }
        }
        exceptionComponent.setVisible(true);
    }

    public static void setChildren(Component parent, Component... children) {
        removeAllChildren(parent);
        for (Component child : children) {
            child.setParent(parent);
        }
    }

    public static void addChildren(Component parent, Component... children) {
        for (Component child : children) {
            child.setParent(parent);
        }
    }

    public static HttpSession getHttpSession(Component component) {
        Desktop d = component.getDesktop();
        if (d == null) {
            logger.error("no desktop for component: " + component);
        }
        Session s = d.getSession();
        Object o = s.getNativeSession();
        return (HttpSession) o;
    }

    public static String getLang(Component component) {
        String lang = "en";
        try {
            lang = ((HttpServletRequest) component.getDesktop().getExecution().getNativeRequest()).getLocale()
                    .getLanguage();
        } catch (Exception e) {}
        return StringUtils.isBlank(lang) ? "en" : lang;
    }
}
